package cn.gy.gift.service.impl;

import cn.gy.gift.client.LoginUserClient;
import cn.gy.gift.domain.Employee;
import cn.gy.gift.domain.LoginUser;
import cn.gy.gift.domain.Tenant;
import cn.gy.gift.domain.TenantMeal;
import cn.gy.gift.enums.SystemErrorCode;
import cn.gy.gift.exception.BusinessException;
import cn.gy.gift.mapper.TenantMapper;
import cn.gy.gift.service.IEmployeeService;
import cn.gy.gift.service.ITenantMealService;
import cn.gy.gift.service.ITenantService;
import cn.gy.gift.util.AjaxResult;
import cn.gy.gift.util.encrypt.MD5;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gy
 * @since 2024-07-19
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    /**
     1.做重名验证
     2.做自动审核 --商户名字 logo图片
     3.验证管理员用户名是否重复
     4.生成商户数据和 商户与套餐的中间表
     5.生成employee数据
     6.发起远程调用生成 登录数据

     */
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private IEmployeeService employeeService;

    //中间表数据
    @Autowired
    private ITenantMealService tenantMealService;

    @Autowired
    private LoginUserClient loginUserClient;


    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    //开启全局事务，只在需要调用其他分支数据库的服务中配置
    public void settlement(Tenant tenant) {
        //生成数据前检查工作
        checkData(tenant);

        //生成Employee数据
        Employee admin = tenant.getAdmin();
        //admin.setLoginId();
        admin.setPassword(MD5.getMD5(admin.getPassword()));
        admin.setInputTime(new Date());
        admin.setState(1);//1 正常

        //组装登录信息对象-->远程调用
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(admin.getUsername());
        loginUser.setPassword(admin.getPassword());
        loginUser.setEmail(admin.getEmail());
        loginUser.setTel(admin.getTel());
        loginUser.setType(LoginUser.USER_ADMIN);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        //生成employee数据
        //解析调用的结果
        if(!ajaxResult.getSuccess()){
            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_400500);
        }

        //获取远程数据
        Long loginId =Long.valueOf(ajaxResult.getResultObj().toString());
        admin.setLoginId(loginId);

        employeeService.insert(admin);
        //生成租户数据

        tenant.setRegisterTime(new Date());
        tenant.setState(0);//待审核
        tenant.setAdminId(admin.getId());
        super.insert(tenant);
        //生成中间表
        TenantMeal meal = new TenantMeal();
        meal.setMealId(tenant.getMealId());
        meal.setTenantId(tenant.getId());
        meal.setExpireDate(new Date());
        tenantMealService.insert(meal);


    }

    private void checkData(Tenant tenant) {
        // 1.做重名验证
        EntityWrapper<Tenant> wrapper = new EntityWrapper<>();
        wrapper.eq("company_name",tenant.getCompanyName());
        Integer count = tenantMapper.selectCount(wrapper);
        if(count != 0){ //公司名字已经存在
            throw  new BusinessException(SystemErrorCode.RESPONSE_CODE_400002);
        }
        // 2.做自动审核 --商户名字 logo图片
        //3.验证管理员用户名是否重复
        EntityWrapper<Employee> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("username",tenant.getAdmin().getUsername());
        Employee employee = employeeService.selectOne(entityWrapper);
        if(employee !=null){
            throw  new BusinessException(SystemErrorCode.RESPONSE_CODE_400003);
        }
        //4 两次密码是否输入一致，前台已经做了，在这儿省略

    }
}
